// pages/repair/repair.js
Page({
    /**
     * 页面的初始数据
     */
    data: {
        months: [
            0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
        ],
        repairForm: {
            date: "",
            submittingDate: "",
            time: "",
            building: "",
            project: "",
            description: "",
            roomNumber: "",
            sid: "",
            name: "",
            phone_number: "",
        },
        pickerDate: [], // 函数生成最近5天日期
        pickerBuilding: [
            [
                { id: 0, name: '教学办公区' },
                { id: 1, name: '芷兰公寓' },
                { id: 2, name: '东湖公寓' }
            ],
            [
                { id: 10, pid: 0, name: '一教' },
                { id: 11, pid: 0, name: '二教' },
                { id: 12, pid: 0, name: '三教' },
                { id: 13, pid: 0, name: '四教' },
                { id: 14, pid: 0, name: '五教' },
                { id: 15, pid: 0, name: '六教' },
                { id: 16, pid: 0, name: '七教' },
                { id: 17, pid: 0, name: '八教' },
                { id: 18, pid: 0, name: '九教' },
                { id: 19, pid: 0, name: '十教' },
                { id: 20, pid: 0, name: '十一教' },
                { id: 21, pid: 0, name: '十二教' },
                { id: 22, pid: 0, name: '十三教' },
                { id: 23, pid: 0, name: '十四教' },
                { id: 24, pid: 0, name: '十五教' },
                { id: 30, pid: 1, name: '一栋' },
                { id: 31, pid: 1, name: '二栋' },
                { id: 32, pid: 1, name: '三栋' },
                { id: 33, pid: 1, name: '四栋' },
                { id: 34, pid: 1, name: '五栋' },
                { id: 35, pid: 1, name: '六栋' },
                { id: 36, pid: 1, name: '七栋' },
                { id: 37, pid: 1, name: '八栋' },
                { id: 38, pid: 1, name: '九栋' },
                { id: 39, pid: 1, name: '十栋' },
                { id: 40, pid: 1, name: '十一栋' },
                { id: 41, pid: 1, name: '十二栋' },
                { id: 50, pid: 2, name: '一栋' },
                { id: 51, pid: 2, name: '二栋' },
                { id: 52, pid: 2, name: '三栋' },
                { id: 53, pid: 2, name: '四栋' },
                { id: 54, pid: 2, name: '五栋' },
                { id: 55, pid: 2, name: '六栋' },
            ],
        ],
        allLists: {
            date: [ // 用户可见的实际date列表

            ],
            time: [ // 后端送
                { name: '08:00-09:00' },
                { name: '09:00-10:00' },
                { name: '10:00-11:00' },
                { name: '11:00-11:30' },
                { name: '14:30-15:00' },
                { name: '15:00-16:00' },
                { name: '16:00-17:00' }
            ],
            building: [ // 用户可见的实际building列表

            ],
            project: [ // 后端送
                { name: '水工' },
                { name: '电工' },
                { name: '泥工' },
                { name: '木工' },
            ]
        },
        tempImagePaths: [],
    },

    changeColSuper(e) {
        const str = e.target.dataset.listName;
        return {
            list: this.data.allLists[str],
            base: `repairForm.${str}`,
            idx: e.detail.value
        }
    },

    changeSingleCol(e) {
        const { base, list, idx } = this.changeColSuper(e);
        this.setData({
            [base]: list[idx].name
        });
    },

    changeDoubleCol(e) {
        const { base, list, idx } = this.changeColSuper(e);
        this.setData({
            [base]: `${list[0][idx[0]].name} ${list[1][idx[1]].name}`
        });
    },

    changeTripleCol(e) {
        const { base, list, idx } = this.changeColSuper(e);
        var
            year = list[0][idx[0]].name,
            month = `${list[1][idx[1]].name}`,
            date = `${list[2][idx[2]].name}`;
        if (month.length === 1) month = '0' + month;
        if (date.length == 1) date = '0' + date;
        this.setData({
            [base]: `${year}-${month}-${date}`
        });
    },

    viewColKeep(col, idx, colNum, listName, tempListName) { // 保持后面列的一致性
        if (col >= colNum - 1) return;
        var list = this.data[tempListName][col + 1].filter(item => {
            return item.pid === this.data.allLists[listName][col][idx].id;
        });
        this.setData({
            [`allLists.${listName}[${col + 1}]`]: list
        });
        this.viewColKeep(col + 1, 0, colNum, listName, tempListName);
    },

    columnChange(e) {
        var colNum = 1;
        if (e.target.dataset.listName === 'building') colNum = 2;
        else if (e.target.dataset.listName === 'date') colNum = 3;
        this.viewColKeep(
            parseInt(e.detail.column), parseInt(e.detail.value), colNum,
            e.target.dataset.listName, e.target.dataset.tempListName
        );
    },

    isRuiYear(year) {
        if (year % 100 !== 0 && year % 4 === 0)
            return true;
        return year % 400 === 0;
    },

    nextDay(date) {
        const year = date.year,
            month = date.month,
            day = date.day,
            res = { ...date };
        if (month === 12 && day === this.data.months[12])
            res.year++, res.month = 1, res.day = 1;
        else if (month == 2 && this.isRuiYear(year) && res.day === 28)
            res.day++;
        else if (day >= this.data.months[month])
            res.month++, res.day = 1;
        else res.day++;
        return res;
    },

    initPickerDate() { // 初始化pickerDate，并将pickerDate赋给allLists.date
        const now = new Date(); // 获取当前日期
        var myDate = {
            day: now.getDate(),
            month: now.getMonth() + 1,
            year: now.getFullYear()
        }
        // 获取5个日期，并拆分年月日
        const yearSet = new Set(), // 获得出现的所有的年份（不重复）
            monthSet = new Set(), // 获得出现的所有的月份（不重复）
            daySet = []; // 获得出现的所有日期（不重复）
        for (let i = 0; i < 5; i++) {
            yearSet.add(myDate.year);
            monthSet.add(myDate.month);
            daySet.push(myDate.day);
            myDate = this.nextDay(myDate);
        }
        // 获取第一个数组 年
        var arr = [];
        var id = 0;
        yearSet.forEach(item => {
            arr.push({ id: ++id, name: item });
        });
        this.setData({
            'pickerDate': [...this.data.pickerDate, arr]
        });
        // 获取第二个数组 月
        arr = [], id = 10;
        var pid = 1, pre = 0;
        monthSet.forEach(item => {
            if (pre > item) pid++;
            arr.push({ id: ++id, pid: pid, name: item });
            pre = item;
        });
        this.setData({
            'pickerDate': [...this.data.pickerDate, arr]
        });
        // 获取第三个数组 日
        arr = [], id = 100, pid = 11;
        for (let i = 0; i < daySet.length; i++) {
            if (i && daySet[i - 1] > daySet[i]) pid++;
            arr.push({ id: ++id, pid: pid, name: daySet[i] });
        }
        this.setData({
            'pickerDate': [...this.data.pickerDate, arr],
        });
    },

    inputTextBlur(e) {
        const type = e.target.dataset.type;
        this.setData({
            [`repairForm.${type}`]: e.detail.value
        });
    },

    scrollHere(e) {
        wx.pageScrollTo({
            selector: '#input-text-description',
            duration: 300
        });
    },

    popImage(e) {
        const arr = this.data.tempImagePaths;
        arr.splice(e.target.dataset.idx, 1);
        this.setData({
            'tempImagePaths': arr
        });
    },

    myUploadImage() {
        if (this.data.tempImagePaths.length > 2) {
            wx.showToast({
                title: '不可超过3张',
                icon: 'error',
                duration: 1500
            })
            return;
        }
        wx.chooseImage({
            count: 3,
            sourceType: ['album', 'camera'],
            sizeType: ['original', 'compressed'],
            success: (res) => {
                this.setData({
                    'tempImagePaths': [...this.data.tempImagePaths, ...res.tempFilePaths]
                });
            }
        })
    },

    getNowDate() {
        const now = new Date();
        return {
            hour: now.getHours(), date: now.getDate(),
            month: now.getMonth() + 1, year: now.getFullYear()
        }
    },

    repairImagePreview(e) {
        const idx = e.target.dataset.idx;
        wx.previewImage({
            current: this.data.tempImagePaths[idx],
            urls: this.data.tempImagePaths,
        });
    },

    confirmSubmit() {
        wx.showModal({
            title: '提示',
            content: '确定提交吗？请保证信息准确无误',
            complete: (res) => {
                if (res.confirm) this.submitRepair()
            }
        })
    },

    submitRepair() { // 预处理：给定提交时间、100毫秒间隙让bindblur执行完
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        const now = this.getNowDate();
        var month = `${now.month}`,
            date = `${now.date}`;
        if (month.length === 1) month = '0' + month;
        if (date.length === 1) date = '0' + date;
        this.setData({ // 设置提交时间
            'repairForm.submittingDate': `${now.year}-${month}-${date}`
        });
        setTimeout(() => {
            getApp().globalData.getOrders('now').then(() => {
                if (getApp().globalData.nowOrders.length) {
                    wx.showToast({
                        title: '请先完成当前报修',
                        icon: 'none'
                    });
                    return;
                }
                this.realSubmit();
            }).catch(() => wx.showToast({
                title: '出错了',
                icon: 'error'
            }));
        }, 100);
    },

    checkRepairForm() {
        return Object.values(this.data.repairForm).some(item => {
            if (item === '') return true;
            return false;
        });
    },

    checkBeginDate(nowHour) {
        const beginDate = this.data.repairForm.date;
        const beginHour = parseInt(this.data.repairForm.time.slice(0, 2));
        return beginDate === this.data.repairForm.submittingDate && nowHour >= beginHour;
    },

    addRepairRequest(fileIDs) {
        wx.cloud.callFunction({
            name: 'addRepairRequest',
            data: {
                repairForm: this.data.repairForm,
                fileIDs: fileIDs
            }
        }).then(success => {
            if (success.result !== true) throw "submit unsuccessfully";
            wx.showToast({ icon: 'success', title: '提交成功', mask: true, duration: 2000 });
            setTimeout(() => {
                wx.switchTab({
                    url: '../index/index',
                });
                wx.switchTab({
                    url: '../space/space',
                });
            }, 2000);
        }).catch(err => {
            console.error(err);
            wx.showToast({ icon: 'error', title: '提交失败！' });
        });
    },

    realSubmit() {
        if (this.checkRepairForm()) {
            wx.showToast({
                icon: 'none',
                title: '存在未填写的内容',
            });
            return;
        }
        if (this.checkBeginDate(this.getNowDate().hour)) {
            wx.showToast({
                icon: 'none',
                title: '开始时间不得早于当前时间',
            });
            return;
        }
        if (this.data.repairForm.description.length < 5) {
            wx.showToast({
                icon: 'none',
                title: '问题描述文字少于规定字数',
            });
            return;
        }
        if (!this.data.tempImagePaths.length) {
            wx.showToast({
                icon: 'none',
                title: '至少上传一张图片',
            });
            return;
        }
        const fileIDs = [];
        this.data.tempImagePaths.forEach(item => {
            wx.cloud.uploadFile({
                cloudPath: `repairDescriptionPicture/${new Date().getTime()}_${Math.floor(Math.random() * 1000)}.${item.split('.')[1]}`,
                filePath: item,
                success: res => {
                    fileIDs.push(res.fileID);
                    if (fileIDs.length === this.data.tempImagePaths.length)
                        this.addRepairRequest(fileIDs);
                },
                fail: err => {
                    wx.showToast({
                        icon: 'none',
                        title: '图片上传失败',
                    })
                }
            });
        });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.initPickerDate();
        this.setData({
            'allLists.date': this.data.pickerDate.slice(),
            'allLists.building': this.data.pickerBuilding.slice()
        });
        this.viewColKeep(0, 0, 3, 'date', 'pickerDate');
        this.viewColKeep(0, 0, 2, 'building', 'pickerBuilding');
        this.setData({
            'repairForm.sid': getApp().globalData.user.sid,
            'repairForm.name': getApp().globalData.user.name,
            'repairForm.phone_number': getApp().globalData.user.phone_number,
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})